<template>
  <a-modal
    title="新建角色"
    :width="900"
    :visible="visible"
    :confirmLoading="confirmLoading"
    @ok="handleSubmit"
    @cancel="handleCancel"
    :destroyOnClose="true"
  >
    <a-spin :spinning="confirmLoading">
      <a-form :form="form">
        <!-- <a-form-item
          :labelCol="labelCol"
          :wrapperCol="wrapperCol"
          label="唯一识别码"
        >
          <a-input placeholder="唯一识别码" v-decorator="['code', {rules: [{required: true, message: '唯一识别码不能为空！'}]}]" />
        </a-form-item>-->
        <a-form-item :labelCol="labelCol" :wrapperCol="wrapperCol" label="角色名称">
          <a-input
            placeholder="角色名称"
            v-decorator="['name', { rules: [{ required: true, message: '角色名称不能为空！' }] }]"
          />
        </a-form-item>
        <a-form-item :labelCol="labelCol" :wrapperCol="wrapperCol" label="状态">
          <a-select
            placeholder="状态"
            v-decorator="['status', { rules: [{ required: true, message: '状态不能为空！' }] }]"
          >
            <a-select-option value="1">正常</a-select-option>
            <a-select-option value="2">禁用</a-select-option>
          </a-select>
        </a-form-item>
        <a-form-item :labelCol="labelCol" :wrapperCol="wrapperCol" label="描述" hasFeedback>
          <a-textarea :rows="3" placeholder="描述" v-decorator="['description']" />
        </a-form-item>
        <!-- <a-divider /> -->
        <a-tabs default-active-key="1" @change="callback">
          <a-tab-pane key="1" tab="拥有权限">
            <a-form-item label="拥有权限" :labelCol="labelCol" :wrapperCol="wrapperCol">
              <a-row :gutter="16" v-for="(permission, index) in tAllAuthorities" :key="index">
                <a-col :xl="5" :lg="24">{{ permission.name }}：</a-col>
                <a-col :xl="19" :lg="24">
                  <a-checkbox
                    v-if="permission.actions.length > 0"
                    :indeterminate="permission.indeterminate"
                    :checked="permission.checkedAll"
                    @change="onChangeCheckAll($event, permission)"
                  >全选</a-checkbox
                  >
                  <a-checkbox-group
                    :options="permission.actionsFormat"
                    @change="onChangeCheck(permission)"
                    v-model="permission.selected"
                  />
                </a-col>
              </a-row>
            </a-form-item>
          </a-tab-pane>
          <a-tab-pane key="2" tab="菜单配置" force-render>
            <a-form-item label="菜单配置" :labelCol="labelCol" :wrapperCol="wrapperCol">
              <a-tree
                checkable
                v-decorator="['checkedKeys']"
                :tree-data="tAllMenusList"
                @select="onSelect"
                @check="onCheck"
              ></a-tree>
            </a-form-item>
          </a-tab-pane>
          <a-tab-pane key="3" tab="接口权限" force-render>
            <a-spin :spinning="loading">
              <a-table
                ref="table"
                :columns="columns"
                :rowSelection="rowSelection"
                :dataSource="tAllInterface"
                :pagination="pagination"
                @change="handleTableChange"
                rowKey="id"
              >
              </a-table>
            </a-spin>
          </a-tab-pane>
          <a-tab-pane key="4" tab="业务权限" force-render>
            <a-form-item label="配置业务" :labelCol="labelCol" :wrapperCol="wrapperCol" class="category-list">
              <a-checkbox-group @change="onChangeCategory">
                <a-row>
                  <a-col :span="24" v-for="(item, index) in categoryList" :key="index">
                    <a-checkbox :value="item.id"> {{ item.name }}({{ item.code }}) </a-checkbox>
                  </a-col>
                </a-row>
              </a-checkbox-group>
            </a-form-item>
          </a-tab-pane>
        </a-tabs>
      </a-form>
    </a-spin>
  </a-modal>
</template>

<script>
import moment from 'moment'
import { addRoles, addRoleAuthorities, addRoleMenus, getTInterfaceManageList, addRoleServices } from '@/api/role'
import { sqlSelect, sqlInsert } from '@/api/sql'
const plainOptions = ['Apple', 'Pear', 'Orange']
const defaultCheckedList = ['Apple', 'Orange']
export default {
  name: 'CreateForm',
  data () {
    return {
      checkedList1: [],
      checkedKeys: [],
      checkedList: defaultCheckedList,
      indeterminate: true,
      checkAll: false,
      checkedAll: false,
      plainOptions,
      selectedItems: [],
      tAllInterface: [],
      labelCol: {
        xs: { span: 24 },
        sm: { span: 4 }
      },
      wrapperCol: {
        xs: { span: 24 },
        sm: { span: 18 }
      },
      selectedRowKeys: [], // 添加这个属性, 也就是他管理着选中行
      columns: [
        {
          title: '接口号',
          width: 100,
          dataIndex: 'svcCode',
          scopedSlots: { customRender: 'svcCode' },
          sorter: (a, b) => {
            return a.svcCode.localeCompare(b.svcCode)
          } // 排序设置
        },
        {
          title: '接口别名',
          dataIndex: 'shortName'
        },
        {
          title: '接口简称',
          dataIndex: 'name',
          scopedSlots: { customRender: 'name' }
        },
        {
          title: '源系统',
          dataIndex: 'tSystemSource.name'
        },
        {
          title: '目标系统',
          dataIndex: 'tSystemTarget.name'
        },
        // {
        //   title: '接口重发Link',
        //   dataIndex: 'contact_tele',
        //   scopedSlots: { customRender: 'contact_tele' }
        // },
        {
          title: '注册日期',
          dataIndex: 'crt_time',
          scopedSlots: { customRender: 'crt_time' }
        }
      ],
      loading: true,
      visible: false,
      confirmLoading: false,
      // 向后端拉取可以用的操作列表
      permissionList: [
        { label: '新增', value: 'add', defaultChecked: false },
        { label: '查询', value: 'query', defaultChecked: false },
        { label: '修改', value: 'update', defaultChecked: false },
        { label: '详情', value: 'details', defaultChecked: false },
        { label: '列表', value: 'get', defaultChecked: false },
        { label: '删除', value: 'delete', defaultChecked: false },
        { label: '导入', value: 'import', defaultChecked: false },
        { label: '导出', value: 'export', defaultChecked: false }
      ],
      roles: [],
      // tAllAuthorities: [],
      treeData: [],
      // 分页属性
      pagination: {
        defaultPageSize: 10,
        pageNo: 0,
        pageSize: 10, // 默认每页显示数量
        showSizeChanger: true, // 显示可改变每页数量
        showQuickJumper: true, // 是否可以快速跳转至某页
        pageSizeOptions: ['10', '20', '50', '100'], // 每页数量选项
        showTotal: (total) => this.$t('pagination.Total') + ` ${total} ` + this.$t('pagination.items'), // 分页中显示总的数据
        total: 0 // 总条数
      },
      form: this.$form.createForm(this),
      categoryList: [], // 业务列表
      categoryChecked: [] // 选择的业务
    }
  },
  // 父组件传递菜单/权限
  props: {
    tAllMenusList: {
      type: Array,
      default: null
    },
    tAllAuthorities: {
      type: Array,
      default: null
    }
  },

  // props: ['platTye'], // 接收父亲组建的值
  created () {},
  async mounted () {
    // this.getTInterfaceManageList()
    this.categoryList = await this.getCategoryList()
    console.log('this.categoryList', this.categoryList)
  },
  computed: {
    rowSelection () {
      const { selectedRowKeys } = this
      return {
        selectedRowKeys,
        hideDefaultSelections: true,
        onChange: this.onSelectChange
        // onChange: (selectedRowKeys, selectedRows) => {
        //   console.log(`selectedRowKeys: ${selectedRowKeys}`, 'selectedRows: ', selectedRows)
        //   // console.log('选中的选项-----', selectedRowKeys)
        // }
      }
    },
    hasSelected () {
      return this.selectedRowKeys.length > 0
    }
  },
  methods: {
    callback (key) {
      console.log(key)
    },
    onSelectChange (selectedRowKeys) {
      console.log('selectedRowKeys changed: -------------', selectedRowKeys)
      this.selectedRowKeys = selectedRowKeys
    },
    onChangeCheck (permission) {
      console.log('permission------:', permission)
      console.log(permission.selected.length)
      permission.indeterminate = !!permission.selected.length && permission.selected.length < permission.actions.length
      permission.checkedAll = permission.selected.length === permission.actions.length
    },
    onChangeCheckAll (e, permission) {
      console.log('permission:-----', permission)
      Object.assign(permission, {
        selected: e.target.checked ? permission.actions.map((obj) => obj) : [],
        indeterminate: false,
        checkedAll: e.target.checked
      })
    },
    onSelect (selectedKeys, info) {
      console.log('selected', selectedKeys, info)
    },
    onCheck (checkedKeys, info) {
      console.log('onCheck', checkedKeys, info)
      this.checkedKeys = checkedKeys
    },
    // 选中创建时间
    createdChange (value, dateString) {
      console.log('Formatted Selected Time: ', dateString)
    },
    // 选中创建时间
    updateChange (value, dateString) {
      console.log('Formatted Selected Time: ', dateString)
    },
    compareToFirstPassword (rule, value, callback) {
      const form = this.form
      if (value && value !== form.getFieldValue('password_hash')) {
        callback(new Error('两次输入密码不一致'))
        // callback('Two passwords that you enter is inconsistent!')
      } else {
        callback()
      }
    },
    validateToNextPassword (rule, value, callback) {
      const form = this.form
      if (value && this.confirmDirty) {
        form.validateFields(['confirm'], { force: true })
      }
      callback()
    },
    add () {
      this.visible = true
    },
    // 获取接口列表
    getTInterfaceManageList () {
      const filter = { sort: 'id,asc', page: this.pagination.pageNo, size: this.pagination.pageSize }
      getTInterfaceManageList(filter)
        .then((response) => {
          console.log('返回接口列表----ooooo', response.data)
          response.data.forEach((item) => {
            item.crt_time = moment(item.crt_time).format('YYYY-MM-DD HH:mm:ss')
          })
          this.loading = false
          this.pagination.total = Number(response.totalCount)
          // console.log('返回接口列表总数类型', typeof this.pagination.total)
          this.tAllInterface = response.data
        })
        .catch((error) => {
          console.log(error)
        })
    },
    // Promise 写法
    // 第一步：新增角色权限
    tRoleAuthority () {
      return new Promise((resolve, reject) => {
        // 提取想要的对象组成新数组对象
        const tRoleAuthority = []
        this.tAllAuthorities.forEach(function (item) {
          tRoleAuthority.push({ name: item.name, code: item.code, permission: item.selected })
        })
        console.log('重组的新权限对象----', tRoleAuthority)
        const filter = { authority: JSON.stringify(tRoleAuthority) }
        addRoleAuthorities(filter)
          .then((tRoleAuth) => {
            resolve(tRoleAuth)
            console.log('权限列表111111----', tRoleAuth)
          })
          .catch((error) => {
            console.log(error)
          })
      })
    },

    // 第二步：新增角色菜单权限
    tRoleMenu () {
      return new Promise((resolve, reject) => {
        const filter = { menu: this.checkedKeys.join(',') }
        addRoleMenus(filter).then((rolemenu) => {
          // 自己的操作
          resolve(rolemenu)
        })
      })
    },

    // 第三步：新增接口权限
    addRoleServices () {
      return new Promise((resolve, reject) => {
        const filter = { service: this.selectedRowKeys.join(',') }
        addRoleServices(filter).then((roleservice) => {
          // 自己的操作
          resolve(roleservice)
        })
      })
    },

    handleSubmit () {
      console.log('权限', this.tAllAuthorities)
      console.log('tree', this.treeData)
      const {
        form: { validateFields }
      } = this
      this.confirmLoading = true
      validateFields((errors, values) => {
        console.log('提交参数----', values)
        this.tRoleAuthority().then((authority) => {
          console.log('权限参数----', authority)
          // 两个都调成功以后执行的操作
          // 调用角色菜单信息
          this.tRoleMenu().then((roleMenu) => {
            console.log('提交菜单----', roleMenu)
            // 调用角色菜单信息
            this.addRoleServices().then((roleServices) => {
              console.log('接口权限列表----', roleServices)
              values.tRoleAuthority = authority
              values.interface_id = 1
              values.tRoleMenu = roleMenu
              values.tRoleService = roleServices
              // 删除对象中typeId
              delete values.confirm
              // 添加提交的业务
              this.addRoleCategory(this.categoryChecked).then((roleCategory) => {
                values.tRoleCategory = roleCategory
                if (!errors) {
                  console.log('values----', values)
                  addRoles(values).then((res) => {
                    if (res) {
                      // 存储成功、刷新列表
                      this.$emit('ok', values)
                      this.visible = false
                      this.confirmLoading = false
                      this.$notification['success']({
                        message: '提示',
                        description: '数据添加成功！'
                      })
                    }
                  })
                } else {
                  this.confirmLoading = false
                }
              })
            })
          })
        })
      })
    },
    // 分页方法
    handleTableChange (pagination) {
      console.log('分页事件-----------', pagination)
      // this.pagination.current = pagination.current
      this.pagination.pageNo = pagination.current - 1
      this.pagination.pageSize = pagination.pageSize
      this.getTInterfaceManageList()
    },
    handleCancel () {
      this.visible = false
    },

    /**
     * 获取业务列表
     */
    getCategoryList () {
      const params = {
        sql: `select * from t_category`
      }
      return new Promise((resolve, reject) => {
        sqlSelect(params).then(
          (res) => {
            resolve(res)
          },
          (error) => {
            console.log(error)
            resolve(error)
          }
        )
      })
    },

    /**
     * 选择业务
     */
    onChangeCategory (checkedValues) {
      console.log('选择的业务 = ', checkedValues)
      this.categoryChecked = checkedValues
    },

    /**
     * 提交选择的业务
     */
    addRoleCategory (values) {
      console.log(values)
      var params = {
        sql: `insert into t_role_category (category) values ('${values}')`
      }
      return new Promise((resolve, reject) => {
        sqlInsert(params).then(
          (res) => {
            resolve(res)
          },
          (error) => {
            reject(error)
          }
        )
      })
    }
  }
}
</script>

<style lang="less" scoped>
.category-list {
  /deep/.ant-col-24 {
    margin-top: 10px;
  }
}
</style>
